if (window.plus) {
	ready();
} else {
	document.addEventListener('plusready', ready, false);
}

$(function() {
	if (AGENT_CLIENT.WEB) {
		ready();
	}
})

function ready() {
	var thisPage = null,
		user = null,
		html = [],
		addressId = '',
		fromConfirmOrder = getUrlParam('fromConfirmOrder');
	var addAddressPage = function() {
		this.init()
	};

	addAddressPage.prototype = {
		init: function() {
			this.initData();
			this.bindEvent();
		},
		initData: function() {
			var thisModel = this;
			user = getLocalStorage(STORAGE_MANAGER.user);
			if (!user || !user.id) {
				redirect("login.html");
				return false;
			}

			addressId = getUrlParam('id');
			if (addressId) {
				$("#active_title").html("编辑收货地址");
				$.ajax({
					type: "GET",
					url: CONFIG_MANAGER.RequstUrl + "v1/member/address/" + user.id + "/" + addressId,
					async: true,
					beforeSend: function() {
						$.showWaiting();
					}
				}).done(function(data) {
					$("#address").val(data.address);
					$("#consignee").val(data.consignee);
					$("#mobile").val(data.mobile);
					if (data.default_flag) {
						$("#default_flag").prop("checked", true);
					}
					thisModel.loadRegion(data.region_no);
				}).always(function() {
					$.closeWaiting();
				});
			} else {
				$("#deleteAddress").hide();
				thisModel.loadRegion();
			}
		},
		//区域
		loadRegion: function(regionno) {
			$.ajax({
				type: "GET",
				url: CONFIG_MANAGER.RequstUrl + "v1/basic/region/child/CN",
				async: true
			}).done(function(data) {
				if(regionno){
					var province = regionno.substring(0, 4);
				}
				var i = 0;
				var	html = ["<option value='0' selected='selected'>选择省</option>"];
				while (data[i]) {
					html.push("<option " + ((province == data[i].id) ? "selected='selected'" : "") + " value=" + data[i].id + ">" + data[i].name + "</option>");
					i++;
				}
				$("#province").html(html.join(''));
				if (regionno) {					
					var city = regionno.substring(0, 6);
					var country = regionno;					
					$.ajax({
						type: "GET",
						url: CONFIG_MANAGER.RequstUrl + "v1/basic/region/child/" + province,
						async: true
					}).done(function(data) {
						i = 0;
						html = [];
						while (data[i]) {
							html.push("<option " + ((city == data[i].id) ? "selected='selected'" : "") + " value=" + data[i].id + ">" + data[i].name + "</option>");
							i++;
						}
						$("#city").html(html.join(''));

						$.ajax({
							type: "GET",
							url: CONFIG_MANAGER.RequstUrl + "v1/basic/region/child/" + city,
							async: true
						}).done(function(data) {
							i = 0;
							html = [];
							while (data[i]) {
								html.push("<option " + ((country == data[i].id) ? "selected='selected'" : "") + " value=" + data[i].id + ">" + data[i].name + "</option>");
								i++;
							}
							$("#country").html(html.join(''));
						});

					})
				}
			});
		},
		bindEvent: function() {
			//回退
			$("#back").on("click", function() {
				if (AGENT_CLIENT.APP) {
					plus.webview.currentWebview().opener().evalJS("ready()");
					plus.webview.currentWebview().close();
				} else {
					back();
				}
			});

			//清除
			$("#clear").on("click", function() {
				$("input").val("");
				$("select option:first").prop("selected", 'selected');
			});

			//选择省，选择市
			$("#province,#city").on("change", function() {
				selectRegion(this);
			});

			//保存地址
			$("#saveAddress").on("click", function() {
				if ("" == $("#consignee").val()) {
					$.toast("请填写收货人姓名");
					return false;
				}
				if (!isChineseName($("#consignee").val())) {
					$.toast("请填写正确的收货人姓名");
					return false;
				}

				if ("" == $("#mobile").val()) {
					$.toast("请填写手机号");
					return false;
				}
				if (!isTelephone($("#mobile").val())) {
					$.toast("请填写正确的手机号");
					return false;
				}

				if ($("#province").val() == 0) {
					$.toast("请选择省");
					return false;
				}
				if ($("#city").val() == 0) {
					$.toast("请选择市");
					return false;
				}
				if ($("#country").val() == 0) {
					$.toast("请选择区");
					return false;
				}

				if ("" == $("#address").val()) {
					$.toast("请填写收货地址");
					return false;
				}

				var requestData = {
						"region_no": $("#country").val(),
						"address": $("#address").val(),
						"consignee": $("#consignee").val(),
						"mobile": $("#mobile").val(),
						"type": 1,
						"default_flag": $("#default_flag").prop("checked") ? 1 : 0,
					},
					actionUrl = CONFIG_MANAGER.RequstUrl;

				if (addressId) {
					actionUrl += "v1/member/address/edit/" + user.id + "/" + addressId;
				} else {
					actionUrl += "v1/member/address/add/" + user.id;
				}

				$.ajax({
					type: (addressId > 0 ? "PUT" : "POST"),
					url: actionUrl,
					async: true,
					contentType: 'application/json',
					data: JSON.stringify(requestData),
					beforeSend: function() {
						$.showWaiting();
					}
				}).done(function(data) {
					var alertMsg = (addressId > 0) ? "编辑成功" : "添加成功";
					$.alert(alertMsg, function() {
						if (fromConfirmOrder) {
							redirect("../shopcart/confirmOrder.html");
							return;
						}
						if (AGENT_CLIENT.APP) {
							plus.webview.currentWebview().opener().evalJS("ready()");
							plus.webview.currentWebview().close();
						} else {
							redirect('address.html');
						}
					})
				}).fail(function(data) {
					var infor = JSON.parse(data);
					$.toast(infor.Message);
				}).always(function(data) {
					$.closeWaiting();
				});
			});

			//删除地址
			$("#deleteAddress").on("click", function() {
				$.ajax({
					type: "DELETE",
					url: CONFIG_MANAGER.RequstUrl + "v1/member/address/" + user.id + "/" + addressId,
					async: true,
					beforeSend: function(data) {
						$.showWaiting();
					}
				}).done(function(data) {
					$.alert("删除成功", function() {
						if (AGENT_CLIENT.APP) {
							plus.webview.currentWebview().opener().evalJS("ready()");
							plus.webview.currentWebview().close();
						} else {
							redirect('address.html');
						}
						return false;
					});
				}).fail(function(data) {
					$.toast(data.responseJSON.Message);
				}).always(function() {
					$.closeWaiting();
				});
			});
		}
	};

	thisPage = new addAddressPage();

}